package com.ponchware.classes
{

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.GradientType;
	import flash.display.Sprite;
	import flash.geom.Matrix;
	
	import mx.core.UIComponent;
	
	/*
	Gradient colors for ground: #006400, #002800
	*/
	
	public class Terrain extends UIComponent
	{
		// Embedded assets
		[Embed(source="com/ponchware/textures/snow_ground3.png")]
		private var groundTexture:Class;
		
		
		
		//private var container:UIComponent;
		public var ground:Sprite;
		private var terrainPoints:Array;
		private const TERRAIN_SEGMENTS:Number = 25;
		
		public function Terrain()
		{
			super();
		}
		
		protected override function createChildren():void
		{
			super.createChildren();
			//container = new UIComponent();
			ground = new Sprite();
			//container.addChild(ground);
			//this.addChild(container);
			this.addChild(ground);
		}
		
		protected override function updateDisplayList(unscaledWidth:Number, unscaledHeigh:Number):void
		{
			if (!terrainPoints)
				generateTerrainPoints();
				
			drawGround();
		}
		
		
		private function generateTerrainPoints():void
		{
			terrainPoints = new Array();
			for (var i:Number = 0; i < width; i+= width/TERRAIN_SEGMENTS)
			{
				var dy:Number = Math.random() * 100 - 50;
				terrainPoints.push(dy);
			}
		}
		
		public function drawGround():void
		{
			ground.graphics.clear();
			ground.graphics.lineStyle(10);
			
			var texture:Bitmap = new groundTexture();
			ground.graphics.lineBitmapStyle(texture.bitmapData);
			
			
			var matrix:Matrix = new Matrix();
			matrix.createGradientBox(width, height, Math.PI/2, 0, 0);
			ground.graphics.beginGradientFill(GradientType.LINEAR, [0x006400, 0x002800],[1,1], [0,255], matrix);
			//ground.graphics.beginFill(0x0000FF);
			ground.graphics.moveTo(0, height);
			//ground.graphics.lineTo(0, height/2);
			var lastHeight:Number = 0;
			/* for (var i:Number = 0; i < width; i+= width/25)
			{
				var dy:Number = Math.random() * 100;
				ground.graphics.lineTo(i, (height/2-50) + dy);
				lastHeight = (height/2-20) + dy;
			} */
			
			for (var i:Number = 0; i < TERRAIN_SEGMENTS; i++)
			{
				ground.graphics.lineTo(i*width/TERRAIN_SEGMENTS, height/2 + terrainPoints[i]);
				lastHeight = height/2 + terrainPoints[i];
			}
			ground.graphics.lineTo(width, lastHeight);
			ground.graphics.lineTo(width, height);
			ground.graphics.endFill();
		}
	}
	
	
}